<template>
    <div class="header bgColor">
        <!-- 折叠按钮 -->
        <div class="collapse-btn" @click="expend">
            <i class="el-icon-menu"></i>
        </div>
        <div class="logo">甬海e站-内部综合管理平台</div>
        <div class="header-right">
            <div class="header-user-con">
                <!-- 回到工作台 -->
                <div class="btn-workbench" @click="openWorkbench">
                    <el-tooltip effect="dark" :content="'工作台'" placement="bottom">
                        <i class="icon-gongzuotai iconfont"></i>
                    </el-tooltip>
                </div>
                <!-- 待办事项 -->
                <el-badge id="todoNote" class="btn-todo" :value="totalNumber" :max="99">
                    <div class="btn-bell">
                        <el-tooltip effect="dark" :content="totalNumber > 0?`有${totalNumber}条待办，点击查看`:`暂无待办`" placement="bottom">
                            <i class="icon-daibanshixiang iconfont" @click="openTodoMore"></i>
                        </el-tooltip>
                    </div>
                </el-badge>

                <!-- 换肤 -->
                <div class="btn-skin" @click.stop="skinToggle" >
                    <el-tooltip effect="dark" :content="'换肤'" placement="bottom">
                        <i class="icon-huanfu iconfont" data-name="skin_blue"></i>
                    </el-tooltip>
                    <ul  v-if="spectrumPaletteDate ? spectrumPaletteDate.length : null" class="skin-groups" id="color_list" style="display:none;">
                        <li v-for="item in spectrumPaletteDate" :key="item.id" @click="handleChangeSkin(item)"  :style="`background:${item.code}`"> </li>
                    </ul>
                </div>
                <!-- 全屏显示 -->
                <div class="btn-fullscreen" @click="handleFullScreen">
                    <el-tooltip effect="dark" :content="fullscreen?`取消全屏`:`全屏`" placement="bottom">
                        <i class="el-icon-rank"></i>
                    </el-tooltip>
                </div>
                <!-- 消息中心 -->
                <el-badge id="messageNote" :value="unreadCount" :max="99" type="warning">
                    <div class="btn-bell">
                        <el-tooltip effect="dark" :content="unreadCount > 0?`有${unreadCount}条未读消息，点击查看`:`暂无新消息`" placement="bottom">
                            <!--<router-link to="/tabs">

                            </router-link>-->
                            <i class="el-icon-bell" @click="openMessage"></i>
                        </el-tooltip>
                    </div>
                </el-badge>
                <!-- 用户头像 -->
                <div class="user-avator"><img src="@/assets/img/img.jpg"></div>
                <!-- 用户名下拉菜单 -->
                <el-dropdown class="user-name" trigger="click">
                    <span class="el-dropdown-link">
                        {{username}} <i class="el-icon-caret-bottom"></i>
                    </span>
                    <el-dropdown-menu slot="dropdown">
                        <!--<a href="/portal/portalManage.html" target="_blank"> &lt;!&ndash;@click="toPortalManage"&ndash;&gt;
                            <el-dropdown-item class="el-dropdown-item"><i class="el-icon-menu"></i>门户设置</el-dropdown-item>
                        </a>-->
                        <a href="javascript:void(0)" @click="switchDate" class="lista">
                            <el-dropdown-item class="el-dropdown-item"><i class="el-icon-pie-chart"></i>切换日期</el-dropdown-item>
                        </a>
                        <a href="javascript:0;" class="lista">
                            <!--<el-dropdown-item class="el-dropdown-item"><i class="el-icon-goods"></i>主题管理</el-dropdown-item>-->
                            <el-popover
                                    placement="left-start"
                                    title="选择主题"
                                    width="200"
                                    trigger="hover"
                                    >
                                <!-- 解决vue-scroll只给外部元素设置max-height无法滚动的问题（插件缺陷），如果列表元素少于3个，
                                 那么列表容器的高度将小于350px，于是不需要vue-scroll，否则就给它一个固定高度
                                 由于列表数量不确定，我们无法给外部容器一个固定高度，因此需要采用这种解决方案-->
                                <div v-if="themePages.length < 3">
                                    <page-list :themePages="themePages" :tId.sync="tId"></page-list>
                                </div>
                                <div v-else style="height: 350px;">
                                    <vue-scroll
                                            :ops="ops"
                                    >
                                        <page-list :themePages="themePages" :tId.sync="tId"></page-list>
                                    </vue-scroll>
                                </div>

                                <el-dropdown-item class="el-dropdown-item" slot="reference"><i class="el-icon-goods"></i>主题管理</el-dropdown-item>
                            </el-popover>
                        </a>
                        <!--<a href="https://www.baidu.com">
                            <el-dropdown-item class="el-dropdown-item"><i class="el-icon-setting"></i>默认设置</el-dropdown-item>
                        </a>-->
                        <a href="javascript:void(0)" @click="passwordDialogOpen" class="lista" v-if="showPassword==='Y'">
                            <el-dropdown-item class="el-dropdown-item"><i class="el-icon-edit"></i>修改密码</el-dropdown-item>
                        </a>
                        <el-dropdown-item command="loginout" class="el-dropdown-item" @click.native="logout"><i class="el-icon-news"></i>退出登录</el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
            </div>
        </div>

        <el-dialog
                title="修改密码"
                ref="pwd"
                :visible.sync="passwordChangeVisible"
                width="40%"
        >
            <password-change ref="pwdComponent" :passwordChangeVisible.sync="passwordChangeVisible"> </password-change>
            <span slot="footer" class="dialog-footer">
                <el-button @click="passwordChangeVisible = false">取 消</el-button>
                <el-button type="primary" @click="changePassword">确 定</el-button>
            </span>
        </el-dialog>
        <DateChange :dateChangeVisible="dateChangeVisible"></DateChange>
    </div>

</template>
<script>
import bus from '../../common/bus';
import PageList from './PageList';
import PasswordChange from './PasswordChange';
import DateChange from './dateChange';
import appUtil from '~/assets/utils/appUtil.js';
// let Base64 = require('js-base64').Base64;
import { createNamespacedHelpers } from 'vuex';
const { mapState,mapMutations, mapActions } = createNamespacedHelpers('nbhsjModule');
const {  mapState:homemapState,mapMutations:homemapMutations, mapActions:homemapActions} = createNamespacedHelpers('homeModule');
const { mapMutations:homemapMutationsTag, } = createNamespacedHelpers('tagModule');
export default {
    props: ['themeList', 'themeId'],
    data() {
        return {
            tId: this.themeId,
            themePages: [],
            collapse: true,
            fullscreen: false,
            passwordChangeVisible: false,
            dateChangeVisible:false,
            name: '',
            changeSkin: true,
            ops: {
                rail: {
                    opacity: '0',
                    //size: '10px'
                },
                bar: {
                    keepShow: false,
                    onlyShowBarOnScroll: true,
                    background: '#a6a6a6',
                    size: '7px',
                },
            },
            showPassword:'N' // 是否显示修改密码
        };
    },
    components: {
        PageList,
        PasswordChange,
        DateChange
    },
    computed:{
        ...mapState({
            messageList:state => state.messageList,
        }),
        ...homemapState({
            roleTheme:state => state.roleTheme,
            spectrumPaletteDate:state => state.spectrumPaletteDate,
            env:state => state.env
        }),
        username(){
        /*let username = sessionStorage.getItem('ms_username');
        return username ? username : this.name;*/
            let userContext = appUtil.getSes('userContext');
            return userContext.name;
        },
        unreadCount(){
            return this.messageList.unread.length;
        },
        totalNumber(){
            return this.messageList.totalNumber;
        },
        allThemeReceived(){
            let allReceived = true;
            for(let i = 0; i < this.themePages.length; i++){
                if(!this.themePages[i].id){
                    allReceived = false;
                }
            }
            return allReceived;
        }
        
    },
    methods:{
        ...mapMutations([]),
        ...mapActions([]),
        ...homemapMutations(['slibarExpand']),
        ...homemapActions(['getRoleThemeAsync']),
        ...homemapMutationsTag(['switchActiveTag','addTag']),
        
        // 侧边栏折叠
        expend(){
            this.collapse = !this.collapse;
            bus.$emit('collapse', this.collapse);
            this.slibarExpand();
        },
        // 打开切换日期
        switchDate(){
            this.dateChangeVisible = true;
        },
        // 关闭切换日期
        closeDate(){
            // console.log(1);
            this.dateChangeVisible = false;
        },
        // 切换到工作台
        openWorkbench(){
            this.switchActiveTag('index');
        },
        // 打开待办事项更多页面
        openTodoMore(){
            let routeData = this.$router.resolve({
                path: '/MoreTodo',
            });
            let url = window.location.href.split('#')[0]+routeData.href;
            let menu={
                url:url,
                name:'待办事项',
                selfUrl:true
            };
            this.addTag(menu);
            // window.open(routeData.href, '_blank');
        },
        // 全屏事件
        handleFullScreen(){
            const document = process.client ? document : {};
            let element = document.documentElement;
            if (this.fullscreen) {
                if (document.exitFullscreen) {
                    document.exitFullscreen();
                } else if (document.webkitCancelFullScreen) {
                    document.webkitCancelFullScreen();
                } else if (document.mozCancelFullScreen) {
                    document.mozCancelFullScreen();
                } else if (document.msExitFullscreen) {
                    document.msExitFullscreen();
                }
            } else {
                if (element.requestFullscreen) {
                    element.requestFullscreen();
                } else if (element.webkitRequestFullScreen) {
                    element.webkitRequestFullScreen();
                } else if (element.mozRequestFullScreen) {
                    element.mozRequestFullScreen();
                } else if (element.msRequestFullscreen) {
                    // IE11
                    element.msRequestFullscreen();
                }
            }
            this.fullscreen = !this.fullscreen;
        },
        // 切换展示隐藏换肤列表
        skinToggle(){
            this.$nextTick(() => {
                const document = process.client ? document : {};
                let colorGroups = document.getElementsByClassName('skin-groups');
                if(colorGroups[0].style.display==='none'){
                    colorGroups[0].style.display='block';
                }else{
                    colorGroups[0].style.display='none';
                }
            });
        },
        // 点击换肤
        handleChangeSkin(item){
            bus.$emit('setThemeColor',item);
        },
        // 打开消息平台页面
        openMessage(){
            let routeData = this.$router.resolve({
                path: '/Message',
            });
            let url = window.location.href.split('#')[0]+routeData.href;
            url = 'message';
            let menu={
                url:url,
                name:'消息平台',
                selfUrl:true
            };
            this.addTag(menu);
        },
        // 打开修改密码页面
        passwordDialogOpen(){
            this.passwordChangeVisible = true;
        },
        changePassword(){
            this.$refs.pwdComponent.submit();
        },
        // 根据主题列表id 查询详细主题
        roleThemeList(roleTheme){
            roleTheme.forEach( (theme, i) => {
                this.$axios.get('/ptp-engine/apis/engTheme/selectTemplateByThemeId/'+theme.themeId+'').then(res => {
                    let data = JSON.parse(res.data.data);
                    data.id = theme.themeId;
                    //请求了新的主题后，将每个主题的portletList的五个参数标准化为x、y、w、h、i
                    data.portletList = data.portletList.map( (portlet,index) => {
                        return {'x': parseInt(portlet.xpoint), 'y': parseInt(portlet.ypoint), 'h': parseInt(portlet.height),
                            'w': parseInt(portlet.width), 'i': parseInt(index), 'content': portlet.content};
                    });
                    this.$set(this.themePages, i,data);
                }).catch( err => {
                    console.error( err );
                });
            });
        },

        logout(){
        //sessionStorage.clear();
        //console.log(location.href);
            function clearCookie(name) {
                setCookie(name, '', -1);
            }

            function setCookie(cname, cvalue, exdays) {
                const document = process.client ? document : {};
                let d = new Date();
                d.setTime(d.getTime() + (exdays*24*60*60*1000));
                let expires = 'expires='+d.toUTCString();
                document.cookie = cname + '=' + cvalue + '; ' + expires + '; path=/'; // 崔立国 20190226 必须删除根目录（path=/）的cookie。
                document.cookie = cname + '=' + cvalue + '; ' + expires;
            }

            
            

            clearCookie('tokenid');
            clearCookie('username');
            clearCookie('JSESSIONID');
            this.$axios.get('/pf/login/loginOut.do').then((res) => {
                if(res&&res.data&&res.data.url){
                   
                    window.location.href = res.data.url;
                }else{
                    
                    window.location.href = '/pf/portal/login/login.html';
                }
               
            }).catch(() => {
                console.error('退出登录异常');
              
                window.location.href = '/pf/portal/login/login.html';
            });
            
        }
    },
    created(){
        // 关闭修改密码框
        bus.$on('closePasswordDialog', () => {
            this.passwordChangeVisible = false;
        });
        
        // 点击空白处
        process.client ? document.querySelector('body').onclick=function(){
            let ele = document.getElementsByClassName('skin-groups')[0];
            if(ele){
                ele.style.display='none';
            }
            
        } : {};
        // 主题列表详情
        this.roleThemeList(this.roleTheme);
        if(this.env.loginSettings){
            this.showPassword = this.env.loginSettings.split(',')[12];
        }
    },
    mounted(){

    },
    watch: {
        unreadCount: function(newVal, oldVal) {
        //console.log(newVal);
            if (newVal > oldVal) {
                const document = process.client ? document : {};
                let sup = document.querySelector('#messageNote sup');
                //console.log(sup);
                if (sup.classList.contains('blink')) {
                    sup.classList.remove('blink');
                    setTimeout(function () {
                        sup.classList.add('blink');
                    }, 100);
                } else {
                    sup.classList.add('blink');
                }
            }
        },

        themeId( newId ){
            this.tId = newId;
        },

        tId(newId){
            this.$emit('update:themeId', newId);

        }
    }
};
</script>

<style>

    @keyframes blink
    {
        0%   {box-shadow: none;}
        10%  {box-shadow: 0 0 16px 6px #f56c6c;}
        15%  {box-shadow: 0 0 16px 6px #f56c6c;}
        25%  {box-shadow: none;}
        35%  {box-shadow: 0 0 16px 6px #f56c6c;}
        40%  {box-shadow: 0 0 16px 6px #f56c6c;}
        50%  {box-shadow: none;}
        60%  {box-shadow: 0 0 16px 6px #f56c6c;}
        65%  {box-shadow: 0 0 16px 6px #f56c6c;}
        75%  {box-shadow: none;}
        85%  {box-shadow: 0 0 16px 6px #f56c6c;}
        90%  {box-shadow: 0 0 16px 6px #f56c6c;}
        100% {box-shadow: none;}
    }

    @-moz-keyframes blink /* Firefox */
    {
        0%   {box-shadow: none;}
        10%  {box-shadow: 0 0 16px 6px #f56c6c;}
        15%  {box-shadow: 0 0 16px 6px #f56c6c;}
        25%  {box-shadow: none;}
        35%  {box-shadow: 0 0 16px 6px #f56c6c;}
        40%  {box-shadow: 0 0 16px 6px #f56c6c;}
        50%  {box-shadow: none;}
        60%  {box-shadow: 0 0 16px 6px #f56c6c;}
        65%  {box-shadow: 0 0 16px 6px #f56c6c;}
        75%  {box-shadow: none;}
        85%  {box-shadow: 0 0 16px 6px #f56c6c;}
        90%  {box-shadow: 0 0 16px 6px #f56c6c;}
        100% {box-shadow: none;}
    }

    @-webkit-keyframes blink /* Safari 和 Chrome */
    {
        0%   {box-shadow: none;}
        10%  {box-shadow: 0 0 16px 6px #f56c6c;}
        15%  {box-shadow: 0 0 16px 6px #f56c6c;}
        25%  {box-shadow: none;}
        35%  {box-shadow: 0 0 16px 6px #f56c6c;}
        40%  {box-shadow: 0 0 16px 6px #f56c6c;}
        50%  {box-shadow: none;}
        60%  {box-shadow: 0 0 16px 6px #f56c6c;}
        65%  {box-shadow: 0 0 16px 6px #f56c6c;}
        75%  {box-shadow: none;}
        85%  {box-shadow: 0 0 16px 6px #f56c6c;}
        90%  {box-shadow: 0 0 16px 6px #f56c6c;}
        100% {box-shadow: none;}
    }
    #messageNote .blink{
        animation: blink 4s linear;
        -moz-animation: blink 4s linear;
        -webkit-animation: blink 4s linear;
    }
    .el-dialog__body{
        padding: 15px 30px !important;
    }
</style>

<style scoped>
    .header {
        position: relative;
        box-sizing: border-box;
        width: 100%;
        /* height:65px; */
        height: 100%; 
        font-size: 24px;
        color: #fff;
    }
    .collapse-btn{
        float: left;
        padding: 0 21px;
        cursor: pointer;
        line-height: 65px;
    }
    .header .logo{
        float: left;
        width: 380px;
        line-height: 65px;
        letter-spacing: 2px;
    }
    .header-right{
        float: right;
        padding-right: 50px;
    }
    .header-user-con{
        display: flex;
        height: 65px;
        align-items: center;
    }
    .btn-workbench{
        cursor: pointer;
    }
    .btn-workbench, .btn-todo{
        margin-right: 15px;
        margin-left: 8px;
        font-size: 24px;
    }
    .btn-fullscreen{
        transform: rotate(45deg);
        margin-right: 5px;
        font-size: 24px;
    }
    .btn-bell, .btn-fullscreen,.btn-skin{
        position: relative;
        width: 30px;
        height: 30px;
        text-align: center;
        border-radius: 15px;
        cursor: pointer;
    }
    .btn-skin{
        margin-right:10px;
    }
    .btn-bell-badge{
        position: absolute;
        right: 0;
        top: -2px;
        width: 8px;
        height: 8px;
        border-radius: 4px;
        background: #f56c6c;
        color: #fff;
    }
    .btn-bell .el-icon-bell{
        color: #fff;
    }
    .user-name{
        margin-left: 10px;
    }
    .user-avator{
        margin-left: 20px;
    }
    .user-avator img{
        display: block;
        width:38px;
        height:38px;
        border-radius: 50%;
    }
    .el-dropdown-link{
        color: #fff;
        cursor: pointer;
        font-size: 17px;
    }
    .el-dropdown-menu__item{
        text-align: center;
    }
    .skin-groups {
        width:120px;
        position:absolute;
        z-index:100;
        background: #fff;
        padding:5px;
        color: #606266;
        border: 1px solid #EBEEF5;
        border-radius: 4px;
        -webkit-box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }
    .skin-groups li{
        list-style: none;
        cursor: pointer;
        border-radius: 2px;
        width: 20px;
        height:20px;
        display: inline-block;
        margin: 0 5px;
    }

    .lista{
        text-decoration: none;
    }
</style>
